package com.yale.elasticsearch.service.query;

import com.yale.elasticsearch.dto.FuzzyDTO;
import com.yale.elasticsearch.model.entity.UserInfo;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.FuzzyQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.json.JsonData;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 模糊查询
 */
@Slf4j
@Service
public class FuzzyQueryService {

    @Resource
    private ElasticsearchClient elasticsearchClient;
    /**
     * 模糊查询所有以 “三” 结尾的姓名
     */
    public Object fuzzyQuery(FuzzyDTO fuzzyDTO) {
        Object result = "";
        try {
            // 构建模糊查询条件
            FuzzyQuery fuzzyQuery = FuzzyQuery.of(f -> f
                    .field(fuzzyDTO.getField())
                    .value(fuzzyDTO.getKeyword())
                    .fuzziness(fuzzyDTO.getFuzziness())
            );

            // 创建查询请求对象
            SearchRequest searchRequest = SearchRequest.of(s -> s
                    .index(fuzzyDTO.getIndexName())
                    .query(Query.of(q -> q
                            .fuzzy(fuzzyQuery)
                    ))
            );

            // 执行查询
            SearchResponse<JsonData> searchResponse = elasticsearchClient.search(searchRequest, JsonData.class);
             List<UserInfo> userInfoList = new ArrayList<>();
            // 处理响应结果
            if (searchResponse.hits().total().value() > 0) {
                searchResponse.hits().hits().forEach(hit -> {
                    // 将 JSON 转换成对象
                    UserInfo userInfo = JSON.parseObject(hit.source().toJson().toString(), UserInfo.class);
                    userInfoList.add(userInfo);
                    // 输出查询信息
                    log.info("结果：{}",JSON.toJSONString(userInfo));
                });
            }

            result = JSON.toJSONString(userInfoList);

        } catch (IOException e) {
            log.error("Error executing search request: {}" , e.getMessage());
        }
        return result;
    }
//    public Object fuzzyQuery() {
//        Object result = "";
//        try {
//            // 构建查询条件
//            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//            searchSourceBuilder.query(QueryBuilders.fuzzyQuery("name", "三").fuzziness(Fuzziness.AUTO));
//            // 创建查询请求对象，将查询对象配置到其中
//            SearchRequest searchRequest = new SearchRequest("mydlq-user");
//            searchRequest.source(searchSourceBuilder);
//            // 执行查询，然后处理响应结果
//            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//            // 根据状态和数据条数验证是否返回了数据
//            if (RestStatus.OK.equals(searchResponse.status()) && searchResponse.getHits().totalHits > 0) {
//                SearchHits hits = searchResponse.getHits();
//                for (SearchHit hit : hits) {
//                    // 将 JSON 转换成对象
//                    UserInfo userInfo = JSON.parseObject(hit.getSourceAsString(), UserInfo.class);
//                    // 输出查询信息
//                    log.info(userInfo.toString());
//                }
//            }
//            result = searchResponse.getHits();
//        } catch (IOException e) {
//            log.error("", e);
//        }
//        return result;
//    }

}
